# you might need to change these...
from i18ndyn.models  import InternationalText, InternationalChar
from i18ndyn.forms   import InternationalTextFormField


from django.db.models import ForeignKey, Field
from django.dispatch import dispatcher
from django.db.models import signals


class InternationalField(ForeignKey):
    """
    An ``under the hood`` Field that actually defines a foreign key to
    i18n.models.InternationalText
    """
    def __init__(self, unique=False,**kwargs):
        kwargs['unique'] = self.unique = unique
        ForeignKey.__init__(self, **kwargs)

    def contribute_to_class(self, cls, name):

        ForeignKey.contribute_to_class(self, cls, name)
        
        dispatcher.connect(self.__delete__, signal=signals.pre_delete, sender=cls)
 
    def __delete__(self, instance):
        """
        This will ''clean up'' the tables by deleting all the translations.
        If we try deleting the actual text it will die in infinite recursion.
        """
        
        if instance is None:
            raise AttributeError("%s can only be cleared on instances." % self.name)

        if not hasattr(instance, self.get_attname()):
            return

        try:
            itext = self.rel.to.objects.get(pk = getattr(instance, self.get_attname()))
        except:
            return

        # delete translations
        itext.translations.delete()

class InternationalTextField(InternationalField):
    """
    A field for InternationalText.
    """
    def __init__(self, *args, **kwargs):
        kwargs['to'] = InternationalText
        return InternationalField.__init__(self, *args, **kwargs)
    
    def get_manipulator_fields(self, *args, **kwargs):
        return [InternationalTextFormField(field_name = self.name)]



class InternationalCharField(InternationalField):
    """
    An ``under the hood`` Field that actually defines a foreign key to
    i18n.models.InternationalChar
    """
    def __init__(self, *args, **kwargs):
        kwargs['to'] = InternationalChar
        return InternationalField.__init__(self, *args, **kwargs)
    
    def get_manipulator_fields(self, *args, **kwargs):
        return [InternationalTextFormField(field_name = self.name, rows = 1,
                                           model = InternationalChar)]

